package top.cardone.ui.freemarker;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.lang.Nullable;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactory;
import top.cardone.context.ApplicationContextHolder;

import java.io.IOException;

public class FreeMarkerConfigurationFactoryBean extends FreeMarkerConfigurationFactory
        implements FactoryBean<Configuration>, InitializingBean, ResourceLoaderAware {
    @Nullable
    private Configuration configuration;

    @Nullable
    @Value("#{'${top.cardone.ui.freemarker.FreeMarkerConfigurationFactoryBean.templateLoaderPaths:}'.split(',')}")
    private String[] templateLoaderPaths;

    @Nullable
    @Value("${top.cardone.ui.freemarker.FreeMarkerConfigurationFactoryBean.templateLoaderPath:}")
    private String templateLoaderPath;

    @Override
    public void afterPropertiesSet() throws IOException, TemplateException {
        if (StringUtils.isBlank(this.templateLoaderPath)) {
            this.templateLoaderPath = ApplicationContextHolder.getApplicationContext().getEnvironment().getProperty("top.cardone.ui.freemarker.FreeMarkerConfigurationFactoryBean.templateLoaderPath");
        }

        if (ArrayUtils.isEmpty(this.templateLoaderPaths)) {
            this.templateLoaderPaths = StringUtils.split(ApplicationContextHolder.getApplicationContext().getEnvironment().getProperty("top.cardone.ui.freemarker.FreeMarkerConfigurationFactoryBean.templateLoaderPaths"), ",");
        }

        if (StringUtils.isNotBlank(this.templateLoaderPath)) {
            super.setTemplateLoaderPath(this.templateLoaderPath);
        }

        if (ArrayUtils.isNotEmpty(this.templateLoaderPaths)) {
            super.setTemplateLoaderPaths(this.templateLoaderPaths);
        }

        this.configuration = createConfiguration();
    }

    @Override
    @Nullable
    public Configuration getObject() {
        return this.configuration;
    }

    @Override
    public Class<? extends Configuration> getObjectType() {
        return Configuration.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
